employees<template>
  <div class="employees-container">
    <div class="app-container">
      <!-- 卡片1 -->
      <PageTools>
        <template #left>员工总人数:{{ total }}人</template>
        <template #right>
          <el-button type="success" size="mini" @click="$router.push('/import?type=user')">excel导入</el-button>
          <el-button type="warning" size="mini" @click="handleDownload">excel导出</el-button>
          <el-button type="primary" size="mini" @click="showDialog = true">新增员工</el-button>
        </template>
      </PageTools>
      <!-- 卡片2 -->
      <el-card>
        <el-table border :data="list">
          <el-table-column
            label="序号"
            type="index"
            :index="indexMent"
            sortable=""
            width="80"
          />
          <el-table-column label="姓名" prop="username" sortable="" />
          <el-table-column label="头像" prop="staffPhoto" sortable="">
            <template #default="{row}">
              <img v-imgerr="errorImg" :src="row.staffPhoto|| errorImg" alt="" style="width:70px;height:70px;border-radius:50%" @click="handleImgClick(row.staffPhoto)">
            </template>
          </el-table-column>
          <el-table-column label="手机号" prop="mobile" sortable="" />
          <el-table-column label="工号" prop="workNumber" sortable="" />
          <el-table-column label="聘用形式" prop="formOfEmployment" :formatter="formatterMethod" sortable="">
            <!-- <template #default="{ row }">

            </template> -->

          </el-table-column>
          <el-table-column
            label="部门"
            prop="departmentName"
            sortable=""
          />
          <el-table-column label="入职时间" prop="timeOfEntry" sortable="">
            <template #default="{row}">
              <!-- {{ row.timeOfEntry.slice(0,row.timeOfEntry.indexOf('T')) }} -->
              {{ formatTime(row.timeOfEntry,'YYYY-MM-DD') }}
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template #default="{ row }">
              <el-button type="text" size="small" @click="$router.push('/employees/detail/'+row.id)">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="handleAssign(row.id)">角色</el-button>
              <el-button type="text" size="small" @click="delEmployee(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 新增员工对话框 -->
        <add-employee :show-dialog.sync="showDialog" @reload="getEmployees" />
      </el-card>
      <el-pagination
        :current-page="page"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
      <!-- 二维码弹窗 -->
      <el-dialog title="二维码图片预览" :visible="showImg" width="400px" @close="showImg=false">
        <!-- 二维码必须用canvas画布标签 去接收 -->
        <div style="text-align:center">
          <canvas ref="myCanvas" />
        </div>
      </el-dialog>
      <!-- 角色分配弹窗 -->
      <AssignRole :show-role-dialog.sync="showRoleDialog" :user-id="userId" />
    </div>
  </div>
</template>

<script>
import { reqGetEmployeeList, reqDelEmployee } from '@/api/employees'
import AddEmployee from './components/add-employee'
import Enum from '@/api/constant/employees'
import { formatTime } from '@/utils/departments'
import errorImg from '@/assets/common/bigUserHeader.png'
import Qrcode from 'qrcode'
import AssignRole from './components/assign-role'
// console.log(Enum.hireType)
export default {
  name: 'Employees',
  components: {
    AddEmployee,
    AssignRole
  },
  data() {
    return {
      page: 1,
      pagesize: 5,
      list: [],
      total: 0,
      loading: false,
      showDialog: false,
      formatTime,
      errorImg,
      showImg: false,
      showRoleDialog: false,
      userId: ''

    }
  },
  created() {
    this.getEmployees()
  },
  methods: {
    // 点击角色按钮
    handleAssign(id) {
      console.log(id)
      this.userId = id
      this.showRoleDialog = true
    },
    // 二维码
    handleImgClick(url) {
      if (url) {
        this.showImg = true // 弹窗显示
        this.$nextTick(() => {
          Qrcode.toCanvas(this.$refs.myCanvas, url)
        })
      } else {
        // 不存在
        this.$message('去上传图片')
      }
    },
    // 获取员工列表
    async getEmployees() {
      const { data: { rows, total }} = await reqGetEmployeeList(this.page, this.pagesize)
      // console.log(rows)
      this.list = rows
      this.total = total
      this.loading = false
    },
    handleSizeChange(val) {
      this.pagesize = val
      this.page = 1
      this.getEmployees()
    },
    handleCurrentChange(val) {
      this.page = val
      this.getEmployees()
    },
    indexMent(index) {
      return index + 1 + (this.page - 1) * this.pagesize
    },
    // 删除员工
    delEmployee(id) {
      this.$confirm('确定要删除该员工?', '温馨提示').then(async() => {
        await reqDelEmployee(id)
        if (this.list.length === 1 && this.page > 1) {
          this.page--
        }
        this.$message.success('删除成功')
        this.getEmployees()
      }).catch(() => {
        console.log('取消')
      })
    },
    // 格式化聘用形式列
    // row 当前行的数据 { formatterMethod }是row结构出来的
    // column 当前聘用形式列的信息
    // cellValue 单元格展示的数据的值
    // index 索引 (当前用不到可不要,但是前面的column 虽然用不到,但是在占位,所以不可以省略)
    formatterMethod({ formOfEmployment }, column, cellValue) {
      // console.log(formOfEmployment, cellValue)
      // return cellValue === 1 ? '正式' : '非正式'
      // 常量文件的方式控制
      const obj = Enum.hireType.find(item => item.id === +formOfEmployment)
      // console.log(obj)
      // return obj.value
      return obj ? obj.value : '未知'
    },
    // 导出简单的Excel表格
    // handleDownload() {
    //   import('@/vendor/Export2Excel').then(excel => {
    //     excel.export_json_to_excel({
    //       header: ['姓名', '性别', '年龄', '职业'], // 表格的标题
    //       data: [
    //         ['易烊千玺', '男', '22', '演员'],
    //         ['王俊凯', '男', '23', '舞者'],
    //         ['王源', '男', '22', '歌手']
    //       ], // 表格的数据(二维数组) 数据跟着标题一一对应
    //       filename: '学员信息表', // 导出的excel的文件名字
    //       autoWidth: true, // 自适应宽度
    //       bookType: 'xlsx' // 文件扩展名
    //     })
    //   })
    // }
    formart2Array(headersArr, rules, rows) {
      return rows.map(item => {
        // console.log(item)//每一个员工对象
        const arr = []
        headersArr.forEach(str => {
          // console.log(str) //每一个表格的标题 汉字
          const enkey = rules[str] // 英文的键
          // console.log(item[enKey])
          if (enkey === 'formOfEmployment') {
            const o = Enum.hireType.find(subItem => subItem.id === +item[enkey])
            o ? arr.push(o.value) : arr.push('未知')
          } else if (['timeOfEntry', 'correctionTime'].includes(enkey)) {
            arr.push(formatTime(item[enkey], 'YYYY-MM-DD'))
          } else {
            arr.push(item[enkey])
          }
        })
        return arr
      })
    },
    async handleDownload() {
      // 表格的标题
      const headersArr = ['姓名', '手机号', '入职日期', '聘用形式', '转正日期', '工号', '部门']
      const rules = {
        '姓名': 'username',
        '手机号': 'mobile',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }
      // 1,获取到所有员工列表
      const { data: { rows }} = await reqGetEmployeeList(1, this.total)
      // console.log(rows) // 所有的员工列表数据
      const res = this.formart2Array(headersArr, rules, rows)
      // console.log(res)
      import('@/vendor/Export2Excel').then(excel => {
        excel.export_json_to_excel({
          header: headersArr, // 表格的标题
          data: res, // 表格的数据(二维数组) 数据跟着标题一一对应
          filename: '员工信息表', // 导出的excel的文件名字
          autoWidth: true, // 自适应宽度
          bookType: 'xlsx' // 文件扩展名
        })
      })
    }
  }
}
</script>

<style>

</style>
